package com.internetCafes.spms.web.extend.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.internetCafes.spms.common.CommonConstants;
import com.internetCafes.spms.common.base.BaseWebController;
import com.internetCafes.spms.common.module.excel.ExcelUtils;
import com.internetCafes.spms.common.module.excel.po.EntCertiIsoExcel;
import com.internetCafes.spms.common.utils.ShiroUtils;
import com.internetCafes.spms.core.annotation.SysLog;
import com.internetCafes.spms.core.utils.DateUtils;
import com.internetCafes.spms.core.utils.R;
import com.internetCafes.spms.web.extend.model.EntCertiIso;
import com.internetCafes.spms.web.extend.model.EntCertiIsoRenewal;
import com.internetCafes.spms.web.extend.service.IEntCertiIsoRenewalService;
import com.internetCafes.spms.web.extend.service.IEntCertiIsoService;
import com.internetCafes.spms.web.extend.vo.EntCertiIsoVo;
import com.internetCafes.spms.web.sys.model.ResourceInfo;
import com.internetCafes.spms.web.sys.service.ResourceInfoService;
import com.sms.common.util.hutool.core.collection.CollectionUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author LinYe
 * @since 2020-12-08
 */
@RestController
@RequestMapping("/cert/entIso")
public class EntCertiIsoController extends BaseWebController {

    @Autowired
    IEntCertiIsoService entCertiIsoService;

    @Autowired
    ResourceInfoService resourceInfoService;

    @Autowired
    IEntCertiIsoRenewalService entCertiIsoRenewalService;

    @SysLog("保存ISO证书信息")
    @PostMapping("/save")
    @RequiresPermissions("certificate:certificateInfo:save")
    public R save(@RequestBody EntCertiIsoVo entCertiIsoVo) {
        entCertiIsoVo.setStatus(CommonConstants.CommonStatus.DISABLE);
        QueryWrapper<EntCertiIso> entCertiIsoWrapper = new QueryWrapper<>();
        entCertiIsoWrapper.eq("code",entCertiIsoVo.getCode());
        int count = entCertiIsoService.count(entCertiIsoWrapper);
        if (count > 0) {
            return R.error("证书已存在");
        }
        entCertiIsoService.save(entCertiIsoVo);
        if (StringUtils.isNotBlank(entCertiIsoVo.getCertiPic())) {
            ResourceInfo r = new ResourceInfo(ShiroUtils.getUserEntity().getId(), CommonConstants.RESOURCE_PIC_ENT_ISO, entCertiIsoVo.getId(), "pic" + File.separator + entCertiIsoVo.getCertiPic());
            resourceInfoService.save(r);
        }
        return R.ok();
    }

    @SysLog("作废ISO证书信息")
    @PostMapping("/delete")
    @RequiresPermissions("certificate:certificateInfo:delete")
    public R delete(@RequestBody Map<String,Object> params) {
        EntCertiIso entCertiIso = new EntCertiIso();
        entCertiIso.setId(Long.valueOf(String.valueOf(params.get("id"))));
        entCertiIso.setStatus(CommonConstants.CommonStatus.DELETED);
        entCertiIso.setUnableRemark((String) params.get("unableRemark"));
        if (entCertiIsoService.updateById(entCertiIso)) {
            return R.ok();
        } else {
            return R.error("您要删除的证书不存在");
        }
    }

    @SysLog("更新ISO证书信息")
    @PostMapping("/update")
    @RequiresPermissions("certificate:certificateInfo:update")
    public R update(@RequestBody EntCertiIsoVo entCertiIsoVo) {
        if (entCertiIsoService.updateById(entCertiIsoVo)) {
            Map<String,Object> params = new HashMap<>();
            if (entCertiIsoVo.getCertiPic()!=null) {
                params.put("moduleCode", CommonConstants.RESOURCE_PIC_ENT_ISO);
                params.put("moduleId", entCertiIsoVo.getId());
                resourceInfoService.deleteByModuleAndUserId(params);
                if (!"".equals(entCertiIsoVo.getCertiPic())) {
                    ResourceInfo r = new ResourceInfo(ShiroUtils.getUserEntity().getId(), CommonConstants.RESOURCE_PIC_ENT_ISO, entCertiIsoVo.getId(), "pic" + File.separator + entCertiIsoVo.getCertiPic());
                    resourceInfoService.save(r);
                }
            }
            return R.ok();
        } else {
            return R.error("您要更新的证书不存在");
        }
    }

    @GetMapping("/getDetail/{id}")
    @RequiresPermissions("certificate:certificateInfo:info")
    public R get(@PathVariable("id") Long id) {
        EntCertiIso entCertiIso = entCertiIsoService.getById(id);
        if (entCertiIso != null) {
            Map<String,Object>params = new HashMap<>();
            params.put("moduleCode", CommonConstants.RESOURCE_PIC_ENT_ISO);
            params.put("moduleId", id);
            List<ResourceInfo> resourceInfoList = resourceInfoService.query(params);
            EntCertiIsoVo entCertiIsoVo=new EntCertiIsoVo();
            BeanUtils.copyProperties(entCertiIso,entCertiIsoVo);
            if (CollectionUtil.isNotEmpty(resourceInfoList)) {
                entCertiIsoVo.setCertiPic(resourceInfoList.get(0).getPath());
            }
            return R.ok().put("data", entCertiIsoVo);
        } else {
            return R.error("您要查询的证书不存在");
        }
    }

    @PostMapping("/paging")
    @RequiresPermissions("certificate:certificateInfo:list")
    public R paging(@RequestBody EntCertiIsoVo entCertiIsoVo) {
        if (entCertiIsoVo.getStatus()==null) {
            entCertiIsoVo.setStatus(CommonConstants.CommonStatus.DISABLE);
        }
        Page<EntCertiIso> page=new Page<>(entCertiIsoVo.getPageNum(),entCertiIsoVo.getPageSize());
        QueryWrapper<EntCertiIso> entCertiIsoWrapper = new QueryWrapper<>(entCertiIsoVo);
        if (entCertiIsoVo.getName()!=null){
            entCertiIsoWrapper.like("name",entCertiIsoVo.getName());
        }
        if (entCertiIsoVo.getOrderBy()!=null) {
            if ("warningCount".equals(entCertiIsoVo.getOrderBy())) {
                entCertiIsoVo.setOrderBy("expireDate");
            }
            entCertiIsoWrapper.orderBy(entCertiIsoVo.getOrderBy() != null, entCertiIsoVo.isAscFlag(), com.internetCafes.spms.common.utils.StringUtils.HumpToUnderline(entCertiIsoVo.getOrderBy()));
        }
        if (entCertiIsoVo.getWechatParam()!=null){
            entCertiIsoWrapper.and(wrapper -> wrapper.like("name",entCertiIsoVo.getWechatParam()).or().like("code",entCertiIsoVo.getWechatParam()).or().like("release_organ",entCertiIsoVo.getWechatParam()));
        }
        entCertiIsoWrapper.orderBy(true,false,"id");
        if (entCertiIsoVo.getValidityType()!=null) {
            switch (entCertiIsoVo.getValidityType()) {
                case -1:
                    entCertiIsoWrapper.lt("expire_date", new Date());
                    break;
                case 0:
                    entCertiIsoWrapper.gt("expire_date", new Date());
                    entCertiIsoWrapper.lt("expire_date", entCertiIsoVo.getDays() != null && entCertiIsoVo.getDays() != "" ? DateUtils.getBeAfDay(Integer.parseInt(entCertiIsoVo.getDays())) : entCertiIsoVo.getMonths() != null && entCertiIsoVo.getDays() != "" ? DateUtils.getBeAfMonth(Integer.parseInt(entCertiIsoVo.getMonths())) : null);
                    break;
                case 2:
                    entCertiIsoWrapper.lt("expire_date", new Date());
                    entCertiIsoWrapper.or(wrapper -> wrapper.gt("expire_date", new Date()).lt("expire_date", entCertiIsoVo.getDays() != null ? DateUtils.getBeAfDay(Integer.parseInt(entCertiIsoVo.getDays())) : entCertiIsoVo.getMonths() != null ? DateUtils.getBeAfMonth(Integer.parseInt(entCertiIsoVo.getMonths())) : null));
                    break;
            }
        }
        IPage<EntCertiIso> entCertiIsoIPage = entCertiIsoService.page(page,entCertiIsoWrapper);
        List<EntCertiIso> records = entCertiIsoIPage.getRecords();
        for (int i = 0; i < records.size(); i++) {
            EntCertiIso entCertiIso = records.get(i);
            Map<String,Object>params = new HashMap<>();
            params.put("moduleCode", CommonConstants.RESOURCE_PIC_ENT_ISO);
            params.put("moduleId", entCertiIso.getId());
            List<ResourceInfo> resourceInfoList = resourceInfoService.query(params);
            if (CollectionUtil.isNotEmpty(resourceInfoList)) {
                EntCertiIsoVo certiIsoVo = new EntCertiIsoVo();
                BeanUtils.copyProperties(entCertiIso, certiIsoVo);
                certiIsoVo.setCertiPic(resourceInfoList.get(0).getPath());
                records.set(i, certiIsoVo);
            }
        }
        return R.ok().put("data", entCertiIsoIPage);
    }

    @PostMapping("/list")
    @RequiresPermissions("certificate:certificateInfo:list")
    public R list(@RequestBody EntCertiIsoVo entCertiIsoVo) {
        entCertiIsoVo.setStatus(CommonConstants.CommonStatus.DISABLE);
        QueryWrapper<EntCertiIso> entCertiIsoQueryWrapper = new QueryWrapper<>(entCertiIsoVo);
        entCertiIsoQueryWrapper.orderBy(entCertiIsoVo.getOrderBy()!=null,entCertiIsoVo.isAscFlag(),entCertiIsoVo.getOrderBy());
        List<EntCertiIso> list = entCertiIsoService.list(entCertiIsoQueryWrapper);
        return R.ok().put("data", list);
    }

    @PostMapping("/export")
    @RequiresPermissions("certificate:certificateInfo:list")
    public void export(@RequestBody EntCertiIsoVo entCertiIsoVo, HttpServletResponse response) {
        entCertiIsoVo.setStatus(CommonConstants.CommonStatus.DISABLE);
        QueryWrapper<EntCertiIso> entCertiIsoWrapper = new QueryWrapper<>(entCertiIsoVo);
        entCertiIsoWrapper.orderBy(entCertiIsoVo.getOrderBy()!=null,entCertiIsoVo.isAscFlag(),entCertiIsoVo.getOrderBy());
        List<EntCertiIso> list = entCertiIsoService.list(entCertiIsoWrapper);
        try {
            if (list != null && list.size() > 0) {
                List<EntCertiIsoExcel> orderInfoExcelList = new ArrayList<>();
                EntCertiIsoExcel entCertiIsoExcel;
                for (EntCertiIso entCertiIso : list) {
                    entCertiIsoExcel = new EntCertiIsoExcel();
                    BeanUtils.copyProperties(entCertiIso, entCertiIsoExcel);
                    QueryWrapper<EntCertiIsoRenewal> entCertiIsoRenewalWrapper = new QueryWrapper<>();
                    entCertiIsoRenewalWrapper.eq("certificate_id",entCertiIso.getId());
                    List<EntCertiIsoRenewal> entCertiIsoRenewals = entCertiIsoRenewalService.list(entCertiIsoRenewalWrapper);
                    if (CollectionUtils.isNotEmpty(entCertiIsoRenewals)) {
                        for (EntCertiIsoRenewal renewal : entCertiIsoRenewals) {
                            entCertiIsoExcel.setRenewals(renewal.toString());
                        }
                    }
                    orderInfoExcelList.add(entCertiIsoExcel);
                }
                ExcelUtils.exportExcel(orderInfoExcelList, "ISO证书信息统计", "ISO证书信息统计", EntCertiIsoExcel.class, "ISO证书信息统计.xls", response);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @PostMapping("/count")
    @RequiresPermissions("certificate:certificateInfo:list")
    public R count(@ModelAttribute EntCertiIso entCertiIso) {
        entCertiIso.setStatus(CommonConstants.CommonStatus.DISABLE);
        QueryWrapper<EntCertiIso> entCertiIsoQueryWrapper = new QueryWrapper<>(entCertiIso);
        int count = entCertiIsoService.count(entCertiIsoQueryWrapper);
        return R.ok().put("count", count);
    }
}
